<?php

namespace bc\model\wc;

use bc\ar\MActiveRecord;
use bc\model\UserModel;
use bc\util\backend\Page;

class SpreadModel extends MActiveRecord
{
	
	/**
	 * 定义数据表
	 */
	public static function tableName()
	{
		return '{{%wc_spread}}';
	}
	
	/*
	 * 根据医生ID获取医生推荐链表
	 * 参数：
	 * 	tag:0:推荐关注链表 1：用户交易成功，到已过有效期 2：生成交易，但没有核算给推广人 3：核算时过期，不算推广人业绩
	 * */
	public function getSpreadListFromDoctorID($params,$sort,$id,$tag=0,$page=1,$page_size=15)
	{

		$where = "`duser_id` = '{$id}'";
		($tag != 0 && $tag != 1 && $tag != 2 && $tag != 3) ? $where = $where : $where = $where." and `spread_status`= '{$tag}' ";

		$where = $params.' and '.$where;
		$this->sort=$sort;
		$spreadList = $this->getList($where,$page,$page_size);
		$total = $this->getTotal($where);
		$pagination = new Page($total, $page_size);
		$data['pagination'] = $pagination;
		$data ['spreadList'] = $spreadList;
		return $data;
	}

	/*
	 * 设置推广列表状态
	 * $openid:用户openid
	 * $status:0:扫码生成 1:生成交易，但没有核算给推广人 2：付款完成
	 * */
	public function setSpreadStatus($openid,$status)
	{
		$where = array(
			'user_penid' =>$openid
		);

		$spreadRow = $this->getRow($where);
		if(!empty($spreadRow))
		{
			/*生产订单*/
			if($status === 1)
			{
				$data['update_time']=time();
				$data['create_order_time']=time();
				$data['spread_status']=$status;
				$this->modify($data,$spreadRow['id']);
			}elseif($status === 2){
				$data['update_time']=time();
				$data['order_payment_time']=time();
				$data['spread_status']=$status;

				if($spreadRow['effective_time'] < time())
				{
					$data['spread_status']=3;
				}

				$this->modify($data,$spreadRow['id']);
				return true;
			}
		}
		return false;
	}

	/*获取推荐医生id*/
	public function getDoctorId($user_id)
	{
		$whereSpreadModel = array (
			'user_penid' => $user_id
		);

		$this->sort=' id ASC';
		$bookingModelRow = $this->getList ( $whereSpreadModel );

		//判断属于那一个医生推广的用户
		//说明
		foreach($bookingModelRow as $key => $value)
		{
			//第一个符合条件就核算为谁
			if($value['effective_time'] < time() )
			{
				return $value['duser_id'];
			}
		}
		//如果都过期折核算到第一个人
		return $bookingModelRow[0]['duser_id'];
	}

}